import { useState } from 'react';
import { message, Typography } from 'antd';
import DatePickerModal from './DatePickerModal';
import { useDeepCompareEffect } from 'ahooks';
import type { FC } from 'react';

import styles from './index.less';

const { Text } = Typography;

/**
 * 日期选择组件
 * - left: 左侧偏移距离，以em为单位
 */
type TProps = {
  onChange?: TAnyFunction;
  value?: any;
  left?: number;
};

const weekArr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

type TFormData = {
  type: string;
  value?: any[];
};

const CommonDatePicker: FC<TProps> = (props) => {
  const { onChange, value, left = 6 } = props;
  const [visible, setVisible] = useState<boolean>(false);
  const [data, setData] = useState<TFormData>({ type: 'week' });

  const handleSubmit = (val: TFormData) => {
    const { value: resValue } = val;
    if (!(resValue && resValue.length)) {
      message.warn('至少选择一个选项');
    } else {
      setData(val);
      onChange && onChange(val);
      setVisible(false);
    }
  };

  useDeepCompareEffect(() => {
    if (value) {
      setData(value);
    }
  }, [value]);

  const renderText = () => {
    const { type, value: resValue } = data;
    return (
      <div className={styles.showWrap}>
        <div className={styles.showContent}>
          {type === 'week' ? (
            <Text>
              <Text strong className="mr-16">
                按周
              </Text>
              {(resValue as any[]).map((obj) => weekArr[obj]).join('、')}
            </Text>
          ) : (
            <Text>
              <Text strong className="mr-16">
                按月
              </Text>
              {(resValue as any[]).map((obj) => `${obj}号`).join('、')}
            </Text>
          )}
        </div>
        <div className={styles.showBtn} onClick={() => setVisible(true)}>
          编辑
        </div>
      </div>
    );
  };

  return (
    <div className={styles.pickerShowContainer} style={{ paddingLeft: `${left}em` }}>
      <div className={styles.pickerShowBox}>
        {Object.keys(data.value || {}).length > 0 ? (
          renderText()
        ) : (
          <span
            className={styles.choseBtn}
            onClick={() => {
              setVisible(true);
            }}
          >
            点击选择
          </span>
        )}
      </div>

      {visible && (
        <DatePickerModal
          visible={visible}
          data={data}
          onCancel={() => setVisible(false)}
          onSubmit={handleSubmit}
        />
      )}
    </div>
  );
};

export default CommonDatePicker;
